package com.cy.dbinit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.SQLException;

@SpringBootApplication
public class DbInitApplication {

    public static void main(String[] args) {
        SpringApplication.run(DbInitApplication.class, args);
    }

    /*
     * 注入数据源
     * */
    @Autowired
    private DataSource dataSource;

    /*
        spring 的执行流程：
            包扫描创建所有实例 --- 完成所有的依赖注入 --- @PostConstruct所在方法
     */
    @PostConstruct
    public void init() throws SQLException {
        exec("sql/account.sql");
        exec("sql/order.sql");
        exec("sql/seata-server.sql");
        exec("sql/storage.sql");
    }

    private void exec(String sql) throws SQLException {

        //封装资源对象，将sql脚本和启动类类加载器封装成 类路径资源对象
        ClassPathResource cpr = new ClassPathResource(sql, DbInitApplication.class.getClassLoader());
        //二次封装，处理中文编码，封装成 编码资源对象
        EncodedResource resource = new EncodedResource(cpr, "UTF-8");

        //Spring提供的脚本工具类，根据 数据源连接对象 和 资源对象 执行sql脚本
        ScriptUtils.executeSqlScript(dataSource.getConnection(), resource);
    }

}
